﻿using System;
using System.ComponentModel;
using System.Net;
using System.Net.Mail;
using Eassets.Layered.Domain;

namespace Eassets.Service
{
    public class MailService
    {
        private SmtpClient smtp = new SmtpClient();

        //asy
        public void SendMail(Mail mail, string fromMail)
        {
            try
            {
                // Create a MailMessage object
                MailMessage mailMessage = new MailMessage();

                // Define the sender and recipient
                mailMessage.From = new MailAddress(mail.From, mail.FromName);
                mailMessage.To.Add(new MailAddress(mail.To, mail.ToName));

                // Define the subject and body
                mailMessage.Subject = mail.Subject;
                mailMessage.Body = mail.Body;
                mailMessage.IsBodyHtml = true;

                // Configure the mail server
                // smtp = new SmtpClient();
                smtp = new SmtpClient();

                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new NetworkCredential(fromMail, "landofdragon");

                smtp.Send(mailMessage);
            }
            catch (ArgumentException ex)
            {
                // Requierd 'from' and 'to' e-mail Addresses
                throw ex;
            }
            catch (FormatException ex)
            {
                // InValid 'from' and 'to' e-mail Addresses
                throw ex;
            }
            catch (InvalidOperationException ex)
            {
                // InValid SMTP Sever
                throw ex;
            }
            catch (SmtpFailedRecipientException ex)
            {
                // Invalid or No mailbox for 'To' mail Address
                throw ex;

            }
            catch (SmtpException ex)
            {
                // Invalid hostnames result in a WebException InnerException that provides
                // a more descriptive error.
                Exception inner = ex.GetBaseException();
                throw inner;
            }
        }

        void sc_SendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                // Cancelled Message
            }

            else if (e.Error != null)
            {
                //Error Message
            }

            else
            {
                //SUCCESS Message
            }

        }

    }
}
